<template>
    <div style="color:red;font-size:30px;">HELLO TEST</div>
    <div class="detail-container">
        <!-- 返回按钮 -->
        <div class="back-section">
            <el-button type="text" @click="router.back()" class="back-btn">
                <i class="el-icon-arrow-left"></i> 返回列表
            </el-button>
        </div>

        <!-- 帖子详情 -->
        <div class="post-detail-card">
            <div class="post-header">
                <div class="user-info">
                    <el-avatar :src="postDetail.avatar" :size="50" class="user-avatar">
                        {{ postDetail.nickname?.charAt(0) }}
                    </el-avatar>
                    <div class="user-details">
                        <div class="username">{{ postDetail.nickname }}</div>
                        <div class="post-time">{{ formatDate(postDetail.gmtCreate) }}</div>
                    </div>
                </div>
                <div class="post-actions">
                    <el-button type="text" size="small" class="action-btn">
                        <i class="el-icon-star-off"></i>
                    </el-button>
                    <el-button type="text" size="small" class="action-btn">
                        <i class="el-icon-share"></i>
                    </el-button>
                </div>
            </div>

            <div class="post-content">
                <h1 class="post-title">{{ postDetail.content }}</h1>
            </div>
        </div>

        <!-- 回复列表 -->
        <div class="replies-section">
            <div class="section-header">
                <h2 class="section-title">
                    <i class="el-icon-chat-dot-round"></i>
                    所有回复 ({{ replies.length }})
                </h2>
            </div>

            <div class="replies-list">
                <div v-for="reply in replies" :key="reply.id" class="reply-card">
                    <div class="reply-header">
                        <div class="user-info">
                            <el-avatar :src="reply.avatar" :size="36" class="user-avatar">
                                {{ reply.nickname?.charAt(0) }}
                            </el-avatar>
                            <div class="user-details">
                                <div class="username">{{ reply.nickname }}</div>
                                <div class="reply-time">{{ formatDate(reply.gmtCreate) }}</div>
                            </div>
                        </div>
                    </div>

                    <div class="reply-content">
                        <template v-if="reply.parentId && reply.parentId !== postId">
                            <span style="color:#888;font-size:0.95em;">
                                回復 @{{ getParentNickname(reply.parentId) }}：
                            </span>
                        </template>
                        <p>{{ reply.content }}</p>
                    </div>

                    <div class="reply-actions">
                        <el-button type="text" size="small" class="action-btn">
                            <i class="el-icon-thumbs-up"></i> 点赞
                        </el-button>
                        <el-button type="text" size="small" class="action-btn"
                                   @click="replyToId = reply.id">
                            <i class="el-icon-chat-dot-round"></i> 回复
                        </el-button>
                    </div>
                </div>

                <div v-if="replies.length === 0" class="empty-replies">
                    <i class="el-icon-chat-dot-round"></i>
                    <p>还没有回复，快来抢沙发吧！</p>
                </div>
            </div>
        </div>

        <!-- 回复表单 -->
        <div class="reply-form-section">
            <!-- 这里加提示 -->
            <div v-if="replyToId" style="color:#667eea;margin-bottom:8px;">
                正在回复评论：{{ replyToId }}
                <el-button type="text" size="small" @click="replyToId = ''">取消</el-button>
            </div>
            <div class="form-header">
                <h3 class="form-title">
                    <i class="el-icon-edit"></i>
                    发表回复
                </h3>
            </div>

            <el-form :model="replyForm" class="reply-form">
                <el-form-item>
                    <el-input
                            v-model="replyForm.content"
                            type="textarea"
                            :rows="4"
                            placeholder="写下你的想法..."
                            class="reply-textarea"
                    />
                </el-form-item>

                <el-form-item>
                    <el-button
                            type="primary"
                            size="large"
                            @click="submitReply"
                            :loading="submitting"
                            class="submit-btn"
                    >
                        <i class="el-icon-s-promotion"></i>
                        发表回复
                    </el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, watchEffect } from 'vue'
import { getHelpDetail, getHelpList, addHelp } from '../api/help'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()
const postId = route.params.id
let replyToId = ref("") // 记录当前要回复的评论id，默认空字符串

// 防禦性 watchEffect，保證 replyToId 永遠是 ref
watchEffect(() => {
  if (typeof replyToId !== 'object' || !('value' in replyToId)) {
    console.warn('[防禦] replyToId 被污染，強制重置為 ref')
    replyToId = ref("")
  }
})

const postDetail = ref({
    content: '',
    nickname: '',
    gmtCreate: '',
    avatar: ''
})
const replies = ref([])
const replyForm = ref({ content: '' })
const submitting = ref(false)

const formatDate = (dateStr) => {
    if (!dateStr) return ''
    const date = new Date(dateStr)
    const now = new Date()
    const diff = now - date

    if (diff < 60000) return '刚刚'
    if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
    if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
    if (diff < 2592000000) return `${Math.floor(diff / 86400000)}天前`

    return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
}

const getParentNickname = (parentId) => {
  if (!parentId) return ''
  if (parentId === postId) return postDetail.value.nickname
  const parent = replies.value.find(r => r.id === parentId)
  return parent ? parent.nickname : '未知'
}

const fetchPostDetail = async () => {
    try {
        const res = await getHelpDetail(postId)
        if (res.data && res.data.success) {
            postDetail.value = res.data.data.comment || res.data.data
        }
    } catch (error) {
        console.error('获取帖子详情失败:', error)
    }
}

const fetchReplies = async () => {
    try {
        const res = await getHelpList(1, 20, postId)
        if (res.data && res.data.success) {
            replies.value = res.data.data.list || []
        }
    } catch (error) {
        console.error('获取回复列表失败:', error)
    }
}

const submitReply = async () => {
    if (!replyForm.value.content.trim()) {
        ElMessage.warning('请输入回复内容')
        return
    }

    try {
        submitting.value = true
        const token = localStorage.getItem('token')
        if (!token) {
            ElMessage.error('请先登录')
            return
        }

        await addHelp({
            content: replyForm.value.content,
            courseId: postId,
            parentId: replyToId.value || ""
        }, token)
        ElMessage.success('回复成功！')
        replyForm.value.content = ""
        await fetchReplies()
    } catch (error) {
        console.error('提交回复失败:', error)
        ElMessage.error('回复失败，请重试')
    } finally {
        submitting.value = false
    }
}

onMounted(() => {
    fetchPostDetail()
    fetchReplies()
})
</script>

<style scoped>
.detail-container {
    max-width: 1000px;
    margin: 0 auto;
    padding: 20px;
    background: #f8f9fa;
    min-height: 100vh;
}

.back-section {
    margin-bottom: 20px;
}

.back-btn {
    font-size: 1rem;
    color: #6c757d;
    padding: 8px 16px;
    border-radius: 8px;
    transition: all 0.3s ease;
}

.back-btn:hover {
    background: #e9ecef;
    color: #495057;
}

.post-detail-card {
    background: white;
    border-radius: 16px;
    padding: 32px;
    margin-bottom: 24px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.08);
    border: 1px solid #e9ecef;
}

.post-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 24px;
}

.user-info {
    display: flex;
    align-items: center;
    gap: 16px;
}

.user-avatar {
    border: 3px solid #f8f9fa;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.user-details {
    display: flex;
    flex-direction: column;
}

.username {
    font-weight: 600;
    color: #2c3e50;
    font-size: 1.1rem;
}

.post-time {
    font-size: 0.9rem;
    color: #6c757d;
    margin-top: 4px;
}

.post-actions {
    display: flex;
    gap: 8px;
}

.action-btn {
    color: #6c757d;
    transition: color 0.2s ease;
}

.action-btn:hover {
    color: #667eea;
}

.post-content {
    margin-bottom: 0;
}

.post-title {
    font-size: 1.8rem;
    font-weight: 700;
    color: #2c3e50;
    margin: 0;
    line-height: 1.4;
}

.replies-section {
    background: white;
    border-radius: 16px;
    padding: 32px;
    margin-bottom: 24px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.08);
    border: 1px solid #e9ecef;
}

.section-header {
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 2px solid #f8f9fa;
}

.section-title {
    font-size: 1.4rem;
    font-weight: 600;
    color: #2c3e50;
    margin: 0;
    display: flex;
    align-items: center;
    gap: 8px;
}

.section-title i {
    color: #667eea;
}

.replies-list {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.reply-card {
    padding: 20px;
    border-radius: 12px;
    background: #f8f9fa;
    border: 1px solid #e9ecef;
    transition: all 0.3s ease;
}

.reply-card:hover {
    background: #ffffff;
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.reply-header {
    margin-bottom: 12px;
}

.reply-content {
    margin-bottom: 16px;
}

.reply-content p {
    margin: 0;
    font-size: 1rem;
    line-height: 1.6;
    color: #495057;
}

.reply-actions {
    display: flex;
    gap: 16px;
}

.empty-replies {
    text-align: center;
    padding: 60px 20px;
    color: #6c757d;
}

.empty-replies i {
    font-size: 3rem;
    margin-bottom: 16px;
    opacity: 0.5;
}

.empty-replies p {
    font-size: 1.1rem;
    margin: 0;
}

.reply-form-section {
    background: white;
    border-radius: 16px;
    padding: 32px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.08);
    border: 1px solid #e9ecef;
}

.form-header {
    margin-bottom: 24px;
}

.form-title {
    font-size: 1.3rem;
    font-weight: 600;
    color: #2c3e50;
    margin: 0;
    display: flex;
    align-items: center;
    gap: 8px;
}

.form-title i {
    color: #667eea;
}

.reply-textarea {
    border-radius: 12px;
    border: 2px solid #e9ecef;
    transition: border-color 0.3s ease;
}

.reply-textarea:focus {
    border-color: #667eea;
}

.submit-btn {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
    border-radius: 12px;
    padding: 12px 30px;
    font-size: 1.1rem;
    font-weight: 600;
    transition: all 0.3s ease;
}

.submit-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
}

/* 响应式设计 */
@media (max-width: 768px) {
    .detail-container {
        padding: 10px;
    }

    .post-detail-card,
    .replies-section,
    .reply-form-section {
        padding: 20px;
    }

    .post-title {
        font-size: 1.5rem;
    }
}
</style>